package io.webfolder.cdp.channel;

import static com.neovisionaries.ws.client.DualStackMode.IPV4_ONLY;

import java.io.IOException;

import com.neovisionaries.ws.client.WebSocket;
import com.neovisionaries.ws.client.WebSocketFactory;

import io.webfolder.cdp.exception.CdpException;
import io.webfolder.cdp.session.MessageHandler;
import io.webfolder.cdp.session.SessionFactory;

public class NvWebSocketFactory implements ChannelFactory, AutoCloseable {

	private static final int CONNECTION_TIMEOUT = 10_000; // 10 seconds

	private final WebSocketFactory factory = new WebSocketFactory();

	private WebSocket webSocket;

	public NvWebSocketFactory() {
		this(CONNECTION_TIMEOUT);
	}

	public NvWebSocketFactory(int connectionTimeout) {
		factory.setConnectionTimeout(connectionTimeout);
		factory.setDualStackMode(IPV4_ONLY);
		factory.setVerifyHostname(false);
	}

	@Override
	public Channel createChannel(Connection connection, SessionFactory factory, MessageHandler handler) {
		if (webSocket != null) {
			throw new IllegalStateException();
		}
		String url = ((WebSocketConnection) connection).getUrl();
		try {
			webSocket = this.factory.createSocket(url);
		} catch (IOException e) {
			throw new CdpException(e);
		}
		webSocket.addListener(new NvWebSocketListener(factory, handler));
		return new NvWebSocketChannel(webSocket);
	}

	@Override
	public void close() {
		if (webSocket != null && webSocket.isOpen()) {
			webSocket.disconnect();
		}
	}
}
